package com.clstu.reflection;

import java.lang.reflect.Field;

public class ReflectAccessProperty {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> studentCls = Class.forName("com.clstu.reflection.Student");
        Object o = studentCls.newInstance();
        System.out.println(o);
        System.out.println(studentCls==o.getClass());
        Field name = studentCls.getField("name");
        name.set(o,"along");
        System.out.println(o);
        System.out.println(name.get(o));
        Field age = studentCls.getDeclaredField("age");//得到私有属性
        age.setAccessible(true);//对属性进行爆破
        age.set(null,20);//因为是static修饰的对象,所以可以在对象那里用null,(可以不需要对象来set)
        System.out.println(o);
        System.out.println(age.get(null));//和下面方法一样都可以显示age属性
        System.out.println(age.get(o));//因为age 是static的

    }
}
class Student{
    public String name;
    private static int age;

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                "age='" + age + '\'' +
                '}';
    }
}